package com.itgan.userbackendmanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.itgan.userbackendmanagement.common.enumeration.ErrorCodeEnum;
import com.itgan.userbackendmanagement.common.respondResult.Result;
import com.itgan.userbackendmanagement.exception.BusinessException;
import com.itgan.userbackendmanagement.pojo.dto.LoginDTO;
import com.itgan.userbackendmanagement.pojo.dto.RegisterDTO;
import com.itgan.userbackendmanagement.pojo.entity.User;
import com.itgan.userbackendmanagement.context.BaseContext;
import com.itgan.userbackendmanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

import static com.itgan.userbackendmanagement.constant.MessageConstant.*;
import static com.itgan.userbackendmanagement.constant.UserConstant.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
        @Resource
        private UserService userService;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
        @PostMapping("/login")
        public Result login(@RequestBody LoginDTO loginDTO, HttpServletRequest request){

        User user = userService.doLogin(loginDTO, request);
        if (user==null){
            return Result.error(ACCOUNT_NOT_FOUND);
        }
            log.info("用户：{} 登录了",user.getUserAccount());
            Long currentId = BaseContext.getCurrentId();
            log.info("当前线程Id:{}",currentId);
            Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
            String SessionId = request.getSession().getId();
            log.info("登录时会话id：{}",SessionId);
            log.info("会话中取值：{}",userObj);
            return Result.success(user);

        }

    /**
     * 添加用户
     * @return
     */
        @PostMapping("/save")
        public Result addUser(){
            userService.addUser();
            return Result.success();

        }
        @PostMapping("/register")
        public Result register(@RequestBody RegisterDTO registerDTO){

            if (StringUtils.isAllBlank(registerDTO.getCheckPassword(),registerDTO.getUserAccount(),registerDTO.getCheckPassword())){
                return null;
            }
            int result = userService.register(registerDTO);

            log.info("注册了新用户：{}",registerDTO.getUserAccount());

            return Result.success(result);
        }

        @GetMapping("/current")
        public User getCurrentUser(HttpServletRequest request){
            Long currentId = BaseContext.getCurrentId();
            log.info("当前线程Id:{}",currentId);
            Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
            String SessionId = request.getSession().getId();
            log.info("current时会话id：{}",SessionId);
            User currentUser = (User) userObj;
            if (currentUser == null){
                throw new BusinessException(ErrorCodeEnum.NOT_LOGIN,USER_NOT_LOGIN);
            }
            long userId = currentUser.getId();
            User user = userService.getById(userId);
            log.info("返回的用户数据：{}",user);

            return userService.getSafetyUser(user);
        }

    @GetMapping("/search")
    public Result<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH,"缺少管理员权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return Result.success(list);
    }
    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR,OPERATION_EXCEPTION);
        }
        int result = userService.userLogout(request);
        return Result.success(result);
    }



}
